package com.mego.tzadd.activitys;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.DhcpInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.mego.tzadd.R;
import com.mego.tzadd.database.dbmodel.SystemAllInfo;
import com.mego.tzadd.database.manager.SystemCenter;
import com.mego.tzadd.utils.HttpRequest;
import com.mego.tzadd.utils.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.ui.BottomMenuWindow;
import zuo.biao.library.ui.EditTextInfoActivity;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.util.JSON;
import zuo.biao.library.util.StringUtil;

public class XzwifiActivity extends BaseActivity implements View.OnClickListener, TimeRefresher.OnTimeRefreshListener {

    private final String TAG = "XzwifiActivity";

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    public static Intent createIntent(Context context) {
        return new Intent(context, XzwifiActivity.class);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xzwifi_activity);

        isLocServiceEnable(this);

        initView();
        initData();
        initEvent();

        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    }

    public boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        showShortToast("搜尋WIFI，請開啟位置服務！");

        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent, 213);
        return false;
    }

    WifiManager wifiManager;

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    @Override
    public void onForwardClick(View v) {

    }

    private TextView tv_wifiname;
    private TextView tv_wifimima;
    private ImageView iv_jzwifi;
    private TextView tv_jtname;
    private TextView tv_save;


    @Override
    public void initView() {
        ImageButton ivBaseTabReturn = (ImageButton) findViewById(R.id.ivBaseTabReturn);
        if (ivBaseTabReturn != null) {
            ivBaseTabReturn.setScaleType(ImageView.ScaleType.FIT_START);
        }

        tv_wifiname = (TextView) findViewById(R.id.tv_wifiname);
        tv_wifimima = (TextView) findViewById(R.id.tv_wifimima);
        iv_jzwifi = (ImageView) findViewById(R.id.iv_jzwifi);
        tv_jtname = (TextView) findViewById(R.id.tv_jtname);
        tv_save = (TextView) findViewById(R.id.tv_save);

    }

    String _jtname = "";

    private void editJtName(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NAME
                    , "機台名稱", _jtname, getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NAME
                    , "機台名稱", _jtname);
        }

        toActivity(intent, REQUEST_TO_EDIT_JTNAME, !toWindow);
    }

    String _ssid = "";

    @Override
    public void initData() {

        _ssid = SystemCenter.getInstance().ssid;

        _wifiname = SystemCenter.getInstance().ssid0;
        tv_wifiname.setText(_wifiname);

        SystemAllInfo lastwifi = SystemCenter.getInstance().getSysInfo("lastwifi");
        if (lastwifi != null) {
            SystemAllInfo wifimima = SystemCenter.getInstance().getSysInfo(_wifiname);
            if (wifimima != null) {
                _wifimima = wifimima.getContent();
                tv_wifimima.setText(_wifimima);
            }
        }

    }

    String _wifiname = "";
    String _wifimima = "";
    boolean _jzwifi = true;

    private void editMima(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NAME
                    , getString(R.string.wifimima), _wifimima, getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NAME
                    , getString(R.string.wifimima), _wifimima);
        }

        toActivity(intent, REQUEST_TO_EDIT_MIMA, !toWindow);
    }

    private void editWifi(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NAME
                    , getString(R.string.wifiname), _wifiname, getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NAME
                    , getString(R.string.wifiname), _wifiname);
        }

        toActivity(intent, REQUEST_TO_EDIT_WIFI, !toWindow);
    }

    @Override
    public void initEvent() {
        findViewById(R.id.tv_wifiname).setOnClickListener(this);
        findViewById(R.id.tv_wifimima).setOnClickListener(this);
        findViewById(R.id.iv_jzwifi).setOnClickListener(this);

        findViewById(R.id.tv_jtname).setOnClickListener(this);
        findViewById(R.id.tv_save).setOnClickListener(this);

        findViewById(R.id.tv_dolink).setOnClickListener(this);
        findViewById(R.id.tv_swifi).setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_swifi:
                popWifiname();
                break;
            case R.id.tv_wifiname:
                editWifi(true);
                break;
            case R.id.tv_wifimima:
                editMima(true);
                break;
            case R.id.iv_jzwifi:
                onjzwifi();
                break;
            case R.id.tv_save:
                onSave();
                break;
            case R.id.tv_jtname:
                editJtName(true);//机台名称
                break;
            case R.id.tv_dolink:
                //设置， tcp发送to机台
                onReset();
                sendLinkInfo();
                break;
        }
    }

    List<ScanResult> _wifilist;
    String[] WIFINMAES = null;
    boolean _isscan = false;

    void popWifiname() {
        if (_isscan) {
            return;
        }
        _isscan = true;
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        showProgressDialog("搜索WIFI..");
        wifiManager.startScan();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //发送数据
                try {
                    Thread.sleep(3000);
                    mHandler.sendEmptyMessage(FINISHSSCANWIFI);

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }

    void showwifilist() {
        _wifilist = wifiManager.getScanResults();
        int size = _wifilist.size();
        WIFINMAES = new String[size];
        int i = 0;
        for (ScanResult sr : _wifilist) {
            WIFINMAES[i] = sr.SSID;
            i++;
        }
        toActivity(BottomMenuWindow.createIntent(context, WIFINMAES)
                .putExtra(BottomMenuWindow.INTENT_TITLE, "當前環境 WIFI"), REQUEST_TO_BOTTOM_MENU_0, false);
        _isscan = false;
    }

    private void onjzwifi() {
        _jzwifi = !_jzwifi;
        if (_jzwifi) {
            iv_jzwifi.setBackgroundResource(R.mipmap.btn_checkbox_pressed);
        } else {
            iv_jzwifi.setBackgroundResource(R.mipmap.btn_checkbox_normal);
        }
    }

    private final int REQUEST_TO_EDIT_JTNAME = 34;
    private final int REQUEST_TO_EDIT_MIMA = 35;
    private final int REQUEST_TO_BOTTOM_MENU_0 = 31;

    private final int REQUEST_TO_EDIT_WIFI = 36;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_TO_BOTTOM_MENU_0:
                if (data != null) {
                    int selectedPosition = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (selectedPosition >= 0 && selectedPosition < WIFINMAES.length) {
                        _wifiname = WIFINMAES[selectedPosition];
                        tv_wifiname.setText(_wifiname);

                        SystemAllInfo wifimima = SystemCenter.getInstance().getSysInfo(_wifiname);
                        if (wifimima != null) {
                            _wifimima = wifimima.getContent();
                            tv_wifimima.setText(_wifimima);
                        }
                    }
                }
                break;
            case REQUEST_TO_EDIT_JTNAME:
                if (data != null) {
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    _jtname = name;
                    tv_jtname.setText(name);
                }
                break;
            case REQUEST_TO_EDIT_MIMA:
                if (data != null) {
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    _wifimima = name;
                    tv_wifimima.setText(name);
                }
                break;
            case REQUEST_TO_EDIT_WIFI:
                if (data != null) {
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    _wifiname = name;
                    tv_wifiname.setText(name);
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void onSave() {
        if (_timenum > 0) {
            showShortToast("請重啟裝置，重新設置環境WIFI");
            return;
        }

        if (_rmsg.isEmpty() || !_rmsg.contains("AT+CWJAP=")) {
            showShortToast("設置失敗，請返回上一步，重新連接機台WIFI!");
            return;
        }

//        new AlertDialog(this, "", "確認已經連上正常上網網絡？", "確認", "取消", 11, this).show();
        doSave();
    }

    boolean _isadding = false;

    void doSave() {
//        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//        String ssid = wifiInfo.getSSID();
//        if (ssid.compareTo(SystemCenter.getInstance().ssid0) != 0 ) {
//            showShortToast("請連接回WIFI["+ SystemCenter.getInstance().ssid0 + "]再選擇保存!");
//            return;
//        }

        if (_isadding) {
            return;
        }

        _isadding = true;
        showProgressDialog(R.string.saving);
        String jt_serial0 = "";
        String kind = "";
        String jt_serial = "";
        if (_ssid.contains("DF-COMPANY")) {
            jt_serial0 = "DF-COMPANY";
            kind = "DF";
            jt_serial = _ssid.replace("DF-COMPANY_", "");
        } else if (_ssid.contains("AI-COMPANY")) {
            kind = "AI";
            jt_serial0 = "AI-COMPANY";
            jt_serial = _ssid.replace("AI-COMPANY_", "");
        }  else if (_ssid.contains("DF-THINKER")) {
            kind = "DF";
            jt_serial0 = "DF-THINKER";
            jt_serial = _ssid.replace("DF-THINKER_", "");
        } else {
            kind = "AI";
            jt_serial0 = "AI-THINKER";
            jt_serial = _ssid.replace("AI-THINKER_", "");
        }

        try {
            HttpRequest.addjt(SystemCenter.getInstance().adminid, jt_serial, _jtname, jt_serial0, kind, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    if (code == 1) {
                        setResult(RESULT_OK);
                        showShortToast("機台保存成功！");
                        _isadding = false;
                        finish();
                    } else if (code == -1) {
                        _isadding = false;
                        showShortToast("错误的用户ID！");
                    } else if (code == -2) {
                        _isadding = false;
                        setResult(RESULT_OK);
                        showShortToast("已更新機台名稱保存！");
                        finish();
                    }
                    dismissProgressDialog();
                }
            });
        } catch (Exception e1) {
            dismissProgressDialog();
            showShortToast("請連接回行動網路或可連網之WIFI再選擇保存!");
            _isadding = false;
        }
    }

    int _checknum = 0; //检查次数
    boolean _isCheckjtonline = false;

    void doCheckjtonline() {
        //2秒进入1次； 前10秒不要检查
        _checknum++;
        if (_checknum < 5 || _isCheckjtonline) {
            return;
        }
        String jt_serial0 = "";
        String kind = "";
        String jt_serial = "";
        if (_ssid.contains("DF-COMPANY")) {
            jt_serial0 = "DF-COMPANY";
            kind = "DF";
            jt_serial = _ssid.replace("DF-COMPANY_", "");
        } else if (_ssid.contains("AI-COMPANY")) {
            kind = "AI";
            jt_serial0 = "AI-COMPANY";
            jt_serial = _ssid.replace("AI-COMPANY_", "");
        }  else if (_ssid.contains("DF-THINKER")) {
            kind = "DF";
            jt_serial0 = "DF-THINKER";
            jt_serial = _ssid.replace("DF-THINKER_", "");
        } else {
            kind = "AI";
            jt_serial0 = "AI-THINKER";
            jt_serial = _ssid.replace("AI-THINKER_", "");
        }
        _isCheckjtonline = true;
        try {
            HttpRequest.checkjtonline(jt_serial, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    dismissProgressDialog();
                    _isCheckjtonline = false;
                    if (code == 1) {
                        _checknum = 100;
                        mHandler.sendEmptyMessage(REFRESHLIST);
                    } else if (_checknum > 10) {
                        _checknum = 100;
                        Toast.makeText(XzwifiActivity.this, "機台超時沒有上線，請再重新啟動裝置， 以及確認 wifi 密碼，重新設置！", Toast.LENGTH_LONG).show();
                        finish();
                    }
                }
            });
        } catch (Exception e1) {
            _isCheckjtonline = false;
        }
    }

    private String intToIp(int paramInt) {
        return (paramInt & 0xFF) + "." + (0xFF & paramInt >> 8) + "." + (0xFF & paramInt >> 16) + "."
                + (0xFF & paramInt >> 24);
    }

    private WifiInfo wifiInfo;
    private DhcpInfo dhcpInfo;
    private ConnectThread ct = null;
    String jt_ssid = "";

    void onReset() {
        dhcpInfo = wifiManager.getDhcpInfo();
        wifiInfo = wifiManager.getConnectionInfo();
        jt_ssid = wifiInfo.getSSID();
        _gatewayIP = intToIp(dhcpInfo.gateway);
        if (intToIp(dhcpInfo.gateway).compareToIgnoreCase("192.168.4.1") != 0) {
            showShortToast("裝置網關錯誤, 請返回重新設置！" + intToIp(dhcpInfo.gateway));
            finish();
            return;
        }

        if (ct != null) {
//            ct.interrupt();
//            ct = null;
            return;
        }
        ct = new ConnectThread();
        ct.start();
    }

    private final int REFRESHLIST = 26;
    private final int FINISHSEND = 27;
    private final int CHECKNET = 28;
    private final int FINISHSSCANWIFI = 29;
    private final int RESTARTWIFI = 30;
    private final int CHECKJTONLINE = 31;

    boolean _isnet = false;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == REFRESHLIST) {
                //已tcp发送给设备
                //关闭wifi，断开機台wifi，
//                _isnet = true;
                dismissProgressDialog();
                tv_save.setText("保存");
                tv_save.setTextColor(Color.parseColor("#FFFFFFFF"));
                _timenum = 0;

            } else if (msg.what == CHECKJTONLINE) {
                dismissProgressDialog();
                showProgressDialog("等待機台上線中...");

                wifiManager.setWifiEnabled(false);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //发送数据
                        try {
                            Thread.sleep(10000);
                            mHandler.sendEmptyMessage(RESTARTWIFI);

                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }).start();

            }  else if (msg.what == RESTARTWIFI) {
                wifiManager.setWifiEnabled(true);

                _checknum = 0;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //发送数据
                        while (_checknum < 30) {
                            try {
                                Thread.sleep(2000);
                                WifiInfo wifiInfo2 = wifiManager.getConnectionInfo();
                                String ssid = wifiInfo2.getSSID();
                                if (jt_ssid.compareToIgnoreCase(ssid) == 0) {
                                    mHandler.sendEmptyMessage(CHECKJTONLINE);
                                    break;
                                }
                                doCheckjtonline();
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();

            } else if (msg.what == FINISHSEND) {
                showShortToast("設置命令發送！");
                dismissProgressDialog();
            } else if (msg.what ==  CHECKNET) {
                if (_checking || _rmsg.isEmpty() || !_isnet) {
                    return;
                }
                _checking = true;
                boolean isnet = Utils.isNetPingUsable();
                if (isnet) {
                    dismissProgressDialog();
                    tv_save.setText("保存");
                    tv_save.setTextColor(Color.parseColor("#FFFFFFFF"));
                    _timenum = 0;
                }
                _checking = false;
            } else if (msg.what == FINISHSSCANWIFI) {
                dismissProgressDialog();
                showwifilist();
            }
        }
    };

    boolean _checking = false;

    boolean sendLinkInfo() {
        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "lastwifi", _wifiname));
        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, _wifiname, _wifimima));

        //需延迟2秒再发
        final String msg = String.format("AT+CWJAP=\"%s\",\"%s\"", _wifiname, _wifimima);
        new Thread(new Runnable() {
            @Override
            public void run() {
                //发送数据
                try {
                    Thread.sleep(2000);
                    if (ct == null || ct.outputStream == null) {
                        showShortToast("裝置設置錯誤，請返回第一步驟，確認已連接裝置wifi，或者手機4G網路沒有關閉！");
                        return;
                    }

                    ct.outputStream.write(msg.getBytes());
                    mHandler.sendEmptyMessage(FINISHSEND);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    showShortToast("裝置設置錯誤，請返回第一步驟，確認已連接裝置wifi，或者手機4G網路沒有關閉！");
                    e.printStackTrace();
                    dismissProgressDialog();
                }
            }
        }).start();

        return true;
    }

    private String _gatewayIP = "192.168.4.1"; //机台网关
    String _rmsg = "";

    @Override
    public void onTimerStart() {

    }

    int _timenum = 1000000;

    @Override
    public void onTimerRefresh() {
        // 刷新
//        if (_timenum > 0 && _timenum <= 10) {
//            tv_save.setText(_timenum + "");
//        }

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo == null && SystemCenter.getInstance().ssid.equals(wifiInfo.getSSID())) {
            return;
        }

        if (_timenum > 0) {
            mHandler.sendEmptyMessage(CHECKNET);
        }

    }

    @Override
    public void onTimerStop() {

    }

    class ConnectThread extends Thread {
        public Socket socket = null;        //定义socket
        public OutputStream outputStream = null;    //定义输出流（发送）
        public InputStream inputStream = null;    //定义输入流（接收）

        public void run() {
            socket = null;
            try {
                socket = new Socket(_gatewayIP, 8080);
//                socket = new Socket("192.168.31.139", 8901);
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (socket == null) {
                return;
            }

            //获取输出流
            try {
                outputStream = socket.getOutputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                while (true) {
                    final byte[] buffer = new byte[1024];//创建接收缓冲区
                    if (socket.isClosed()) {
                        return;
                    }
                    inputStream = socket.getInputStream();
                    if (inputStream == null) {
                        continue;
                    }
                    final int len = inputStream.read(buffer);//数据读出来，并且返回数据的长度
                    _rmsg = new String(buffer, "UTF-8");
                    if (!_rmsg.isEmpty() && _rmsg.contains("AT+CWJAP=")) {
                        mHandler.sendEmptyMessage(CHECKJTONLINE);
                    }

                    runOnUiThread(new Runnable()//不允许其他线程直接操作组件，用提供的此方法可以
                    {
                        public void run() {

                        }
                    });
                }
            } catch (IOException e) {

            }

        }
    }

}

